﻿using System;
using System.Reflection;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using HTF_HMI.HTF_HMI;

namespace HTF_HMI
{
   public class HTF_DAL
    {
       private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
       private static string connStr = ConfigReader.getDBString();
       
       private string sql = "";

       public DataTable GetProductDetail()
       {
           DataTable data = new DataTable();
           return data;
       }

        // 查询钢坯数据。
        public DataTable GetBillet(QueryArgs arg, bool bInFurnace)
        {
            DataTable data = new DataTable();

            // 查询炉内钢坯信息
            if (bInFurnace)
                sql = string.Format("select * From furnace_billet_data_tb where out_time is NULL order by id DESC");

            // 查询已出炉钢坯信息
            else {
                sql = " select * From furnace_billet_data_tb where out_time is not NULL ";
                sql += string.Format("and out_time < '{0}' and out_time > '{1}'", 
                    arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            data = ExecuteDataTable(sql);
            return data;
        }

        // 查询钢坯数据。
        public DataTable GetBillet(bool bInFurnace)
        {
            DataTable data = new DataTable();

            // 查询炉内钢坯信息
            if (bInFurnace)
                sql = string.Format("select * from ACT_BILLET where LeaveTime is NULL order by ID DESC");

            // 查询已出炉钢坯信息,只查询前一天
            else
            {
                sql = " select * from ACT_BILLET where LeaveTime is not NULL and LeaveTime >convert(varchar(10), getdate(), 120)+' 00:00:00'";
              
            }

            data = ExecuteDataTable(sql);
            return data;
        }

        // 查询钢坯数据。
        public DataTable GetBilletInAct()
        {
            DataTable data = new DataTable();
            string sql = string.Format("select * from ACT_BILLET where LeaveTime is NULL order by ID DESC");

            data = ExecuteDataTable(sql);
            return data;
        }

        // 查询钢坯数据。
        public DataTable GetBilletOutAct(string startTime,string endTime)
        {
            DataTable data = new DataTable();
            string sql = string.Format(" select * from ACT_BILLET where  LeaveTime  between '"+startTime+"' and '"+ endTime+"'");

            data = ExecuteDataTable(sql);
            return data;
        }

        // 查询炉内映像。
        public DataTable GetBilletImage()
        {
            DataTable data = new DataTable();
            string sql = string.Format("select * from L1COMM.dbo.X_L1_REAL_STEP a left join ACT_BILLET b on  a.BilletNo=b.BilletNo  order by StepID asc");

            data = ExecuteDataTable(sql);
            return data;
        }

        // 查询计划数据。
        public DataTable GetBatchInfo(int iNumBatch)
        {
            DataTable dtPlanNo = new DataTable();

            int iTopRecords = 100 * iNumBatch;
            sql = "select top " + iNumBatch.ToString() + " plan_no from (select top " 
                + iTopRecords.ToString() + " * from plan_tb order by ID desc)a group by plan_no";
            dtPlanNo = ExecuteDataTable(sql);

            DataTable dtBatch = new DataTable();
            dtBatch.Columns.Add("PLAN_NO", System.Type.GetType("System.String"));
            dtBatch.Columns.Add("REV_TIME", System.Type.GetType("System.String"));
            dtBatch.Columns.Add("Counts", System.Type.GetType("System.String"));
            dtBatch.Columns.Add("IS_COMPLETED_1", System.Type.GetType("System.String"));
            dtBatch.Columns.Add("IS_COMPLETED_0", System.Type.GetType("System.String"));
            dtBatch.Columns.Add("IS_COMPLETED_2", System.Type.GetType("System.String"));
            dtBatch.Columns.Add("IS_COMPLETED_3", System.Type.GetType("System.String"));
            dtBatch.Columns.Add("IS_COMPLETED_4", System.Type.GetType("System.String"));


            //dtBatch.Columns.Add("Min", System.Type.GetType("System.Double"));

            for (int i = 0; i < dtPlanNo.Rows.Count; i++)
            {
                DataRow dr = dtBatch.NewRow();
                string strPlanNo = dtPlanNo.Rows[i][0].ToString();
                dr["PLAN_NO"] = strPlanNo;

                sql = "select top 1 REV_TIME from plan_tb where plan_no = '" + strPlanNo + "' order by id desc";
                DataTable dtRevTime = ExecuteDataTable(sql);
                dr["REV_TIME"] = dtRevTime.Rows[0][0].ToString();

                sql = "select count(*) from plan_tb where plan_no = '" + strPlanNo + "'";
                DataTable dtCount1 = ExecuteDataTable(sql);
                dr["Counts"] = dtCount1.Rows[0][0].ToString();

                // 已入炉计划
                sql = "select count(is_completed) from plan_tb where is_completed = 1 and plan_no = '" + strPlanNo + "'";
                DataTable dtIsCompleted_1 = ExecuteDataTable(sql);
                dr["IS_COMPLETED_1"] = dtIsCompleted_1.Rows[0][0].ToString();

                // 未入炉计划
                sql = "select count(is_completed) from plan_tb where is_completed = 0 and plan_no = '" + strPlanNo + "'";
                DataTable dtIsCompleted_0 = ExecuteDataTable(sql);
                dr["IS_COMPLETED_0"] = dtIsCompleted_0.Rows[0][0].ToString();

                // 撤销计划
                sql = "select count(is_completed) from plan_tb where is_completed = 2 and plan_no = '" + strPlanNo + "'";
                DataTable dtIsCompleted_2 = ExecuteDataTable(sql);
                dr["IS_COMPLETED_2"] = dtIsCompleted_2.Rows[0][0].ToString();

                // 剔除
                sql = "select count(is_completed) from plan_tb where is_completed = 3 and plan_no = '" + strPlanNo + "'";
                DataTable dtIsCompleted_3 = ExecuteDataTable(sql);
                dr["IS_COMPLETED_3"] = dtIsCompleted_3.Rows[0][0].ToString();

                // 其他强制完成
                sql = "select count(is_completed) from plan_tb where is_completed > 3 and plan_no = '" + strPlanNo + "'";
                DataTable dtIsCompleted_4 = ExecuteDataTable(sql);
                dr["IS_COMPLETED_4"] = dtIsCompleted_4.Rows[0][0].ToString();
                dtBatch.Rows.Add(dr);
            }

            return dtBatch;
        }


        public DataTable GetBatchInfo(string startTime,string  endTime ,string batchNo)
        {
            DataTable dtBatch = new DataTable();
           
            sql = "select  * from ACT_BATCH where 1=1 ";
            if (!string.IsNullOrEmpty(startTime))
            {
                sql = sql + " and RecordTime>'" + startTime + "'";
            }
            if (!string.IsNullOrEmpty(endTime))
            {
                sql = sql + " and RecordTime<'" + endTime + "'";
            }
            if (!string.IsNullOrEmpty(batchNo))
            {
                sql = sql + " and RollingBatchNo like '%" + batchNo + "%'";
            }
            dtBatch = ExecuteDataTable(sql); 
            return dtBatch;
        }

        public DataTable GetReportInfo(string date, string crew,string shift)
        {
            DataTable dtBatch = new DataTable();

            sql = "select  * from ACT_Report where 1=1 ";
            if (!string.IsNullOrEmpty(date))
            {
                sql = sql + " and ReportDate ='" + DateTime.Parse(date).ToString("yyyy-MM-dd") +"'";
            }           
            if (!string.IsNullOrEmpty(crew))
            {
                sql = sql + " and CrewId = '" + crew + "'";
            }
            if (!string.IsNullOrEmpty(shift))
            {
                sql = sql + " and ShiftNo = '" + shift + "'";
            }
            dtBatch = ExecuteDataTable(sql);
            return dtBatch;
        }


        public DataTable GetPlan(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string whereClause = " 1=1 ";

          string start = DateTime.Now.AddDays(-3).ToString("yyyyMMdd") + "000000";
           string end = DateTime.Now.ToString("yyyyMMdd") + "235959";

          if (arg.checkTime)
               whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", arg.StopTime.ToString("yyyyMMddHHmmss"), arg.StartTime.ToString("yyyyMMddHHmmss"));
           else
              whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", end, start);
           
           if (arg.checkPackageNo)
               whereClause = string.Format(" PACKAGE_NO  Like '%{0}%' ", arg.PackageNo);

           sql = string.Format("Select PACKAGE_NO,Count(*) NUM ,min(STEEL_GRADE) STEEL_GRADE,min(ST_NO) ST_NO,min(SAMPLE_NO)SAMPLE_NO,min(PLAN_NO)PLAN_NO,sum(SHEET_WEIGHT_T)SHEET_WEIGHT_T,"
                   + " max(OUT_MAT_WT)OUT_MAT_WT, max(OUT_MAT_LEN)OUT_MAT_LEN,max(OUT_MAT_WID)OUT_MAT_WID,max(OUT_MAT_THICK)OUT_MAT_THICK From( select * from HTF_PLAN_PRODUCE   Where {0} AND FLAG=0 ) Group By PACKAGE_NO  Order By Min(REV_TIME)", whereClause);
          
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetProcedure(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string whereClause = " 1=1 ";

           string start = DateTime.Now.AddDays(-3).ToString("yyyyMMdd") + "000000";
           string end = DateTime.Now.ToString("yyyyMMdd") + "235959";

           if (arg.checkTime)
               whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", arg.StopTime.ToString("yyyyMMddHHmmss"), arg.StartTime.ToString("yyyyMMddHHmmss"));
           else
               whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", end, start);

           if (arg.checkPackageNo)
               whereClause = string.Format(" PACKAGE_NO  Like '%{0}%' ", arg.PackageNo);

           sql = string.Format("select PACKAGE_NO, Count(SHEET_NO)ANUM,sum(SPLATE_WEIGHT)AWEIGHT from HTF_PLATE_DATA  where PACKAGE_NO in (select distinct(package_no)PACKAGE_NO from HTF_PLAN_PRODUCE   Where {0} AND FLAG=0) and HANG_FLAG=0  group by PACKAGE_NO ", whereClause);

           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetProcedure_D(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string whereClause = " 1=1 ";

           string start = DateTime.Now.AddDays(-3).ToString("yyyyMMdd") + "000000";
           string end = DateTime.Now.ToString("yyyyMMdd") + "235959";

           if (arg.checkTime)
               whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", arg.StopTime.ToString("yyyyMMddHHmmss"), arg.StartTime.ToString("yyyyMMddHHmmss"));
           else
               whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", end, start);

           if (arg.checkPackageNo)
               whereClause = string.Format(" PACKAGE_NO  Like '%{0}%' ", arg.PackageNo);

           sql = string.Format("select PACKAGE_NO, Count(SHEET_NO)ANUM,sum(SPLATE_WEIGHT)AWEIGHT from HTF_PLATE_DATA  where PACKAGE_NO in (select distinct(package_no)PACKAGE_NO from HTF_PLAN_PRODUCE Where {0} AND FLAG=0) and HANG_FLAG=1  group by PACKAGE_NO ", whereClause);

           data = ExecuteDataTable(sql);
           return data;
       }



       public DataTable GetPlanDetail(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string start = DateTime.Now.AddDays(-3).ToString("yyyyMMdd") + "000000";
           string end = DateTime.Now.ToString("yyyyMMdd") + "235959";

           string whereClause = "1=1";
           if (arg.checkTime)
               whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", arg.StopTime.ToString("yyyyMMddHHmmss"), arg.StartTime.ToString("yyyyMMddHHmmss"));
           else
               whereClause += string.Format(" and REV_TIME<'{0}' and REV_TIME>'{1}'", end, start);
         
           if (arg.checkPackageNo)
               whereClause = string.Format(" PACKAGE_NO Like '%{0}%' ", arg.PackageNo);
           sql = string.Format("select * from HTF_PLAN_PRODUCE  Where {0} AND FLAG=0 order by SHEET_NO", whereClause);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPackageNoPrinting()
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PRINT_DATA  Where  FLAG=1 order by PACKAGE_NO_SET desc");
           data = ExecuteDataTable(sql);
           if (data.Rows.Count == 0)
           {
               sql = string.Format("select * from HTF_PRINT_DATA  Where  FLAG=2 order by PACKAGE_NO_SET desc");
               data = ExecuteDataTable(sql);
           }
           if (data.Rows.Count == 0)
           {
               sql = string.Format("select * from HTF_PRINT_DATA  order by PACKAGE_NO_SET ");
               data = ExecuteDataTable(sql);
            }
            string packagenoset;
            if (data.Rows.Count > 0)
            {
                packagenoset = data.Rows[0]["PACKAGE_NO_SET"].ToString();
            }
            else
            {
                packagenoset = "no_package_no";
            }
            sql = string.Format("select* from( select distinct(PACKAGE_NO_SET)PACKAGE_NO_SET from HTF_PRINT_DATA  Where  PACKAGE_NO_SET>='{0}' ) order by PACKAGE_NO_SET", packagenoset);
            data = ExecuteDataTable(sql);
            return data;
       }

       public DataTable GetSheetNoPrinting(string PACKAGE_NO_SET)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PRINT_DATA  Where  FLAG!='2' and PACKAGE_NO_SET='{0}'  order by FLAG DESC,SHEET_NO", PACKAGE_NO_SET);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPrintInfo(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string whereClause = " 1=1 ";
           string Btime = DateTime.Now.ToString("yyyy/MM/dd");
           sql = string.Format("select * from HTF_PRINT_DATA  Where  FLAG!='2' AND PLAN_PROC_TIME>=to_date('{0}','yyyy/mm/dd') order by PACKAGE_NO_SET,SHEET_NO", Btime);     
           if (arg.checkTime)
           {
               whereClause += string.Format(" and PLAN_PROC_TIME<=to_date('{0}','yyyy/mm/dd') and PLAN_PROC_TIME>=to_date('{1}','yyyy/mm/dd')", arg.StopTime.ToString("yyyy-MM-dd"), arg.StartTime.ToString("yyyy-MM-dd"));
               sql = string.Format("select * from HTF_PRINT_DATA  Where {0} order by PACKAGE_NO_SET,SHEET_NO", whereClause);
           }
           if (arg.checkPackageNo)
           {
               sql = string.Format("select * from HTF_PRINT_DATA  Where PACKAGE_NO_ACT like '%{0}%' order by SHEET_NO", arg.PackageNo);
           }         
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetProductDetail(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string whereClause = "1=1";
           if (arg.checkTime)
               whereClause += string.Format(" and PRODUCT_TIME<to_date('{0}','yyyy-mm-dd hh24:mi:ss') and PRODUCT_TIME>to_date('{1}','yyyy-mm-dd hh24:mi:ss')", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
           if (arg.checkPackageNo)
               whereClause = string.Format(" PACKAGE_NO  Like '%{0}%'", arg.PackageNo);
           sql = string.Format("select * from HTF_PACKAGE_DATA  Where {0} order by PRODUCT_TIME ", whereClause);
           data = ExecuteDataTable(sql);
           return data;
        }

        public DataTable GetTempratureDetail(QueryArgs arg)
        {
            DataTable data = new DataTable();
            string whereClause = "1=1";
            if (arg.checkTime)
                whereClause += string.Format(" and Rev_time < '{0}' and Rev_time > '{1}'", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
            sql = string.Format("select Rev_time, Fur_Area_id, Temp_act from fur_meas_value_tb Where {0} order by Rev_time ", whereClause);
            data = ExecuteDataTable(sql);
            return data;
        }

        public DataTable GetTemp(QueryArgs arg)
        {
            DataTable data = new DataTable();
            string whereClause = "1=1";
            if (arg.checkTime)
                whereClause += string.Format(" and MeasureTime < '{0}' and MeasureTime > '{1}'", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
            sql = string.Format("select MeasureTime, Area1AvgTemp, Area2AvgTemp,Area3AvgTemp from L1COMM.DBO.X_L1_REALDATA Where {0} order by MeasureTime ", whereClause);
            data = ExecuteDataTable(sql);
            return data;
        }

        public DataTable GetMeasDetail(QueryArgs arg)
        {
            DataTable data = new DataTable();
            string whereClause = "1=1";
            if (arg.checkTime)
                whereClause += string.Format(" and Rev_time < '{0}' and Rev_time > '{1}'", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
            sql = string.Format("select * from meas_value_tb Where {0} order by Rev_time ", whereClause);
            data = ExecuteDataTable(sql);
            return data;
        }

        public DataTable GetGas(QueryArgs arg)
        {
            DataTable data = new DataTable();
            string whereClause = "1=1";
            if (arg.checkTime)
                whereClause += string.Format(" and MeasureTime < '{0}' and MeasureTime > '{1}'", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
            sql = string.Format("select * from L1COMM.DBO.X_L1_REALDATA Where {0} order by MeasureTime ", whereClause);
            data = ExecuteDataTable(sql);
            return data;
        }

        public DataTable GetExitSheetDataRelation(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string whereClause = "1=1";
           string whereClauseA = "1=1";
           DateTime startprint = arg.StartTime.AddHours(-12);
           if (arg.checkTime)
           {
               whereClauseA += string.Format(" and PRODUCT_TIME<to_date('{0}','yyyy-mm-dd hh24:mi:ss') and PRODUCT_TIME>to_date('{1}','yyyy-mm-dd hh24:mi:ss')", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
               whereClause += string.Format(" and FEEDING_TIME<to_date('{0}','yyyy-mm-dd hh24:mi:ss') and FEEDING_TIME>to_date('{1}','yyyy-mm-dd hh24:mi:ss')", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), startprint.ToString("yyyy-MM-dd HH:mm:ss"));
           }
           if (arg.checkPackageNo)
           {
               whereClauseA = string.Format(" PACKAGE_NO  Like '%{0}%'", arg.PackageNo);
               whereClause = string.Format(" PACKAGE_NO Like '%{0}%' ", arg.PackageNo);
           }
           sql = string.Format("select * from HTF_PLATE_DATA t Where PRINT_PACKAGE_NO in( select PACKAGE_NO from HTF_PACKAGE_DATA  Where {0} ) and {1} order by FEEDING_TIME ", whereClauseA, whereClause);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetExitSheetData(QueryArgs arg)
       {
           DataTable data = new DataTable();
           string whereClause = "1=1";
           if (arg.checkTime)
           {
               whereClause += string.Format(" and FEEDING_TIME<to_date('{0}','yyyy-mm-dd hh24:mi:ss') and FEEDING_TIME>to_date('{1}','yyyy-mm-dd hh24:mi:ss')", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
           }
           if (arg.checkPackageNo)
           {
               whereClause = string.Format(" PACKAGE_NO Like '%{0}%' ", arg.PackageNo);
           }
           if (arg.checkSheetNo)
           {
               whereClause = string.Format(" SHEET_NO Like '%{0}%' ", arg.SheetNo);
           }
           sql = string.Format("select * from HTF_PLATE_DATA  Where {0} order by FEEDING_TIME DESC", whereClause);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetSheetPlanAim(string sheetNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from htf_plan_aim  Where SHEET_NO Like '%{0}%'", sheetNo);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetExitSheetData(string sheetNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PLATE_DATA t Where SHEET_NO Like '%{0}%'", sheetNo);
           data = ExecuteDataTable(sql);
           return data;
       }


       public DataTable GetExitSheetsInpackage(string PackageNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PLATE_DATA t Where PRINT_PACKAGE_NO ='{0}' AND PACKAGE_FLAG=0 order by SHEET_NO", PackageNo);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetExitSheetsNotInPackage(QueryArgs arg, string packageno, string sheetnos)
       {
           DataTable data = new DataTable();
           string whereClause = "1=1";
           if (arg.checkTime)
               whereClause += string.Format(" and FEEDING_TIME<to_date('{0}','yyyy-mm-dd hh24:mi:ss') and FEEDING_TIME>to_date('{1}','yyyy-mm-dd hh24:mi:ss') ", arg.StopTime.ToString("yyyy-MM-dd HH:mm:ss"), arg.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
           if (arg.checkSheetNo)
               whereClause = string.Format(" SHEET_NO  Like '%{0}%' ", arg.SheetNo);
           if (sheetnos == "")
             //  sql = string.Format("select * from HTF_PLATE_DATA where (PRINT_PACKAGE_NO is null or PRINT_PACKAGE_NO='{0}') and {1}  and HANG_FLAG=0 AND PACKAGE_FLAG=0",packageno, whereClause);
           sql = string.Format("select * from HTF_PLATE_DATA where {0}  and HANG_FLAG=0 AND PACKAGE_FLAG=0",whereClause);
           
           else
           //    sql = string.Format("select * from(select * from HTF_PLATE_DATA where (PRINT_PACKAGE_NO is null or PRINT_PACKAGE_NO='{1}') and {0} and HANG_FLAG=0 and PACKAGE_FLAG=0 ) where SHEET_NO not in ({2}) order by SHEET_NO", whereClause, packageno, sheetnos);
           sql = string.Format("select * from(select * from HTF_PLATE_DATA where  {0} and HANG_FLAG=0 and PACKAGE_FLAG=0 ) where SHEET_NO not in ({1}) order by SHEET_NO", whereClause,sheetnos);
           
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetExitSheetsNotPrint(string filter)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PLATE_DATA where  SHEET_NO Like '%{0}%' and PRINT_PACKAGE_NO is null and HANG_FLAG=0 and PACKAGE_FLAG=0  order by FEEDING_TIME desc ", filter);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPrintInfo(string sheetno)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PRINT_DATA where SHEET_NO= '{0}' ", sheetno);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetSheetsInPackage(string packageNo, DateTime starttime)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PLATE_DATA t Where (PACKAGE_NO Like '%{0}%' or PACKAGE_NO Is Null) and FEEDING_TIME<to_date('{1}','yyyy-mm-dd hh24:mi:ss') order by ", packageNo,starttime);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetEntrySheetData()
       {
           DataTable data = new DataTable();
           sql = string.Format("select SHEET_NO,PACKAGE_NO,STEEL_GRADE,SHEET_ACTUAL_THICKNESS,SHEET_ACTUAL_WIDTH,"
                + "SHEET_ACTUAL_LENGTH,HEAT_MODE,F_KEEP_TEMP_AIM,F_HEAT_TREAT_KEEP_TIME_AIM,F_TEMP_AIM_TIME, REV_TIME from HTF_PLAN_PRODUCE t where UPPER_FLAG=0 order by REV_TIME");
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetBilletsData(string filter)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from furnace_billet_data_tb where out_time is null and id Like '%{0}%' order by id", filter);
           data = ExecuteDataTable(sql);
           return data;
       }


       public DataTable GetPlanProduce(string sheetNo)
       {
           DataTable data = new DataTable();
            sql = string.Format("select * from HTF_PLAN_PRODUCE where SHEET_NO='{0}'", sheetNo);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPlanProducePackage(string packageNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PLAN_PRODUCE where PACKAGE_NO like '%{0}%'", packageNo);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPackageSampleNo(string sheetNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select distinct(SAMPLE_NO) from( select SAMPLE_NO from HTF_PLAN_PRODUCE where SHEET_NO in ({0}))", sheetNo);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPackagedSampleNo(string printPackageNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select distinct(SAMPLE_NO) from( select SAMPLE_NO from HTF_PLATE_DATA where PACKAGE_FLAG=1 and PRINT_PACKAGE_NO = '{0}' )", printPackageNo);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPlanSample(string sheetNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PLAN_SAMPLE where SHEET_NO like '%{0}%'", sheetNo);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPlanElement(string sheetNo)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from HTF_PLAN_ELEMENT where SHEET_NO='{0}'", sheetNo);
           data = ExecuteDataTable(sql);
           return data;
       }

        public DataTable GetPlan()
        {
            DataTable dt = new DataTable();
            sql = @"select ID, RecordTime,
            PlanNo, PlanSeq, HeatNo, RollingBatchNo, BilletCount, 
                BilletWidth, BilletThickness, BilletLength, BilletWeight, BilletRoute, BilletSteelGrade, SteelGrade, TargetDiameter, 
                BilletSeq, case PlanStatus when 1 then '已入炉' when 0 then '等待入炉' when 2 then '已删除' when 3 then '已跳过' end PlanStatus,EnterSeq 
                from MAIN_PLAN WHERE PlanStatus = 0 order by EnterSeq asc ";
            //sql = " select * from MAIN_PLAN WHERE PlanStatus = 0 order by id asc";
            dt = ExecuteDataTable(sql);
            return dt;
        }

        public void DeletePlan(string strPlanId)
        {
            sql = " delete from MAIN_PLAN WHERE ID = " + strPlanId;
            ExecuteNonQuery(sql);
        }

        public bool DeleteMutiPlan(string strPlanIds)
        {
            sql = " delete from MAIN_PLAN WHERE ID in( " + strPlanIds + ")";
            int result = ExecuteNonQuery(sql);
            if (result > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public string AdjustPlanSeq(string strPlanId,string operate)
        {
            string result = string.Empty;
            DataTable dt = GetPlanBy("ID = " + strPlanId);
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["PlanStatus"].ToString() != "0")
                {
                    result = "该计划已入炉，无法调整入炉顺序！";
                    return result;
                }
            }
            string currentSeq = dt.Rows[0]["EnterSeq"].ToString();
            string sql = string.Empty;
            if (operate.Equals("front"))
            {
                if (currentSeq == "1")
                {
                    result = "该计划已是第一个入炉，无需调整入炉顺序！";
                }
                sql = " update MAIN_PLAN set EnterSeq = EnterSeq+1 WHERE PlanStatus=0 and ID<>" + strPlanId + " and EnterSeq<" + currentSeq + ";";
                sql += " update MAIN_PLAN set EnterSeq = 1 WHERE ID=" + strPlanId + ";";               
            }
            if (operate.Equals("behind"))
            {
                sql = " update MAIN_PLAN set EnterSeq = EnterSeq-1  WHERE PlanStatus=0 and ID<>" + strPlanId + " and EnterSeq>" + currentSeq + ";";
                sql += "update MAIN_PLAN set EnterSeq = (select isnull(max(EnterSeq),0)+1 from MAIN_PLAN WHERE PlanStatus=0 and ID<>"+ strPlanId + ") where id = " + strPlanId + ";";
            }
            if (operate.Equals("up"))
            {
                if (dt.Rows[0]["EnterSeq"].ToString() == "1")
                {
                    result = "该计划已是第一个入炉，无需前移入炉顺序！";
                }
                sql = "update  MAIN_PLAN  SET EnterSeq = EnterSeq+1  WHERE ID in (select top 1 ID  from MAIN_PLAN where  PlanStatus = 0 and EnterSeq<" + currentSeq + " order by EnterSeq desc);";
                sql += "update MAIN_PLAN set EnterSeq = EnterSeq-1 WHERE ID=" + strPlanId + ";";
            }
            if (operate.Equals("down"))
            {
                sql = "update  MAIN_PLAN  SET EnterSeq = EnterSeq-1  WHERE ID in (select top 1 ID  from MAIN_PLAN where  PlanStatus = 0 and EnterSeq>" + currentSeq + " order by EnterSeq asc);";
                sql += "update MAIN_PLAN set EnterSeq = EnterSeq+1 WHERE ID=" + strPlanId + ";";
            }

            int exeCount = ExecuteNonQuery(sql);
            if (exeCount == 0)
            {
                result = "更新顺序失败！";
            }          
            return result;
        }

        public bool GetPlanMatchState()
        {
            string sqlMatch = "select * from PLAN_MATCH";
            DataTable dtMatch = ExecuteDataTable(sqlMatch);

            if (dtMatch.Rows[0][0].ToString() == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public DataTable GetPlanBy(string where)
        {
            DataTable dt = new DataTable();
            string sql = " select * from  MAIN_PLAN  WHERE 1=1 and "+ where ;
            dt = ExecuteDataTable(sql);
            return dt;
        }

        public DataTable GetShutdownReportBy(string where)
        {
            DataTable dt = new DataTable();
            string sql = " select * from  ACT_SHUTDOWN  WHERE 1=1 " + where+ " order by RecordTime desc";
            dt = ExecuteDataTable(sql);
            return dt;
        }  
        public bool DeleteShutdownReport(string strIds)
        {
            sql = " delete from ACT_SHUTDOWN WHERE ID in( " + strIds + ")";
            int result = ExecuteNonQuery(sql);
            if (result > 0)
            {

                foreach (string id in strIds.Split(','))
                {
                    SendBufferToL3("ACT_SHUTDOWN",id,"D");
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool SendBufferToL3(string tableName, string tableId, string eventCode)
        {
            //bool result = true;
            string sql = string.Empty;
            int uniqueId = 0;
            string uniqueSql = "SELECT UniqueID FROM COMM.dbo.SEND_COUNT";
            DataTable uniqueDt = ExecuteDataTable(uniqueSql);
            if (uniqueDt != null && uniqueDt.Rows.Count > 0)
            {
                uniqueId = Int32.Parse(uniqueDt.Rows[0][0].ToString()) + 1;
            }
            switch (tableName)
            {
                case "ACT_SHUTDOWN": 
                    sql = @"INSERT INTO [COMM].[dbo].[ACT_REPORT]           
           (EventCode,[EventTime],[UniqueID],[LineID],[DownStartTime],[DownEndTime],[DownTimeDuration],[DownTimeReason],[ProcessCount])
            SELECT '"+ eventCode + "', [RecordTime],'" + uniqueId.ToString()
                     + @"',[LineID],[DownStartTime],[DownEndTime],[DownTimeDuration],[DownTimeReason],0           
            FROM [dbo].[ACT_REPORT]         
            WHERE ID=" + tableId+ "; ";                  
                    break;
                case "ACT_REJECT"://不能维护
                    sql = @"INSERT INTO [COMM].[dbo].[ACT_EVENT]
           ([EventTime],[UniqueID],[LineID],[PlanNo],[PlanSeq],[HeatNo],[RollingBatchNo],[BilletSeq],[EventCode]
            ,[StatFlag],[RejectReasonCode],[RejectReason],[RejectTime],[ShiftNo]) 
            SELECT   [RecordTime],'" + uniqueId.ToString()
            + @"',[LineID],[PlanNo],[PlanSeq],[HeatNo],[RollingBatchNo],[BilletSeq],'DISPLACED'
            ,[Flag],[ReasonCode],[Reason],[RejectTime],[ShiftNo]            
            FROM [dbo].[ACT_REJECT] WHERE ID=" + tableId + ";";
                    break;
            }
            sql += @"declare @id bigint;select @id = @@IDENTITY; 
                INSERT INTO [COMM].[dbo].[SEND_BUFFER_L3]
                ([UNIQUE_ID],[TABLE_NAME],[DATA_ID]) 
                VALUES( '" + uniqueId.ToString() + @"','" + tableName + "',@id);";

            int result = ExecuteNonQuery(sql);
            if (result>0)
            {
                return true;
            }
            else
            {
                return false;
            }  
        }

        public bool OnManuallPlan(string strPlanNo, int iBatchCount)
        {
            try
            {
                OleDbConnection conn = new OleDbConnection(connStr);
                if (conn.State != ConnectionState.Open)
                    conn.Open();
                OleDbCommand cmd = conn.CreateCommand();
                for (int i = 0; i < iBatchCount; i++)
                {
                    sql = "insert into plan_tb(REV_TIME, PLAN_NO, SHEET_NO, source_tag) values ('"
                        + string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now) + "', '" + strPlanNo + "', '" 
                        + strPlanNo + i.ToString().PadLeft(2, '0') + "', '2')";
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                }

                return true;
            }
            catch (Exception ex)
            {
                //  throw new Exception(sql, ex);
                Logger.ErrorFormat("手动下发计划失败", sql, ex.Message);
                return false;
            }
        }

        public DataTable GetNotCheckSchedule()
       {
           DataTable data = new DataTable();
          sql = " select * from HTF_PRODUCTION_SCHEDULE  WHERE FLAG_PROD=0 AND  FLAG=0 ORDER BY SENDTIME,IDEX ";
           //sql = " select * from HTF_PRODUCTION_SCHEDULE  WHERE  FLAG=0 ORDER BY SENDTIME,IDEX ";
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPackageNotInSchedule(QueryArgs arg, string packages)
       {
           DataTable data = new DataTable();
           string whereClause = "1=1";
           if (arg.checkTime)
               whereClause += string.Format(" and RECV_TIME<to_date('{0}','yyyy-mm-dd hh24:mi:ss') and RECV_TIME>to_date('{1}','yyyy-mm-dd hh24:mi:ss')", arg.StopTime , arg.StartTime );
           if (arg.checkPackageNo)
               whereClause = string.Format(" PACKAGE_NO  Like '%{0}%' ", arg.PackageNo);
           if (packages=="")
              sql = string.Format("select * from HTF_PACKAGE_IN_DATA where {0} and  FLAG_PROD=0 and FLAG=0", whereClause);
              // sql = string.Format("select * from HTF_PACKAGE_IN_DATA where {0} and FLAG=0", whereClause);
          else
             sql = string.Format("select * from(select * from HTF_PACKAGE_IN_DATA where {0} and  FLAG_PROD=0 and FLAG=0 ) where PACKAGE_NO not in ({1}) order by RECV_TIME,PACKAGE_NO", whereClause, packages);
           //sql = string.Format("select * from(select * from HTF_PACKAGE_IN_DATA where {0} and FLAG=0 ) where PACKAGE_NO not in ({1}) order by RECV_TIME,PACKAGE_NO", whereClause, packages);           
           
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable GetPackageforSchedule(string packages)
       {
           DataTable data = new DataTable();
           if (packages=="")
            sql = string.Format("select * from HTF_PACKAGE_IN_DATA where FLAG_PROD=0 and FLAG=0 ", packages);
               // sql = string.Format("select * from HTF_PACKAGE_IN_DATA where FLAG=0 ", packages);
           else
           sql = string.Format("select * from( select * from HTF_PACKAGE_IN_DATA where FLAG_PROD=0 and FLAG=0) where PACKAGE_NO in ({0}) order by RECV_TIME,PACKAGE_NO", packages);
         //  sql = string.Format("select * from( select * from HTF_PACKAGE_IN_DATA where  FLAG=0) where PACKAGE_NO in ({0}) order by RECV_TIME,PACKAGE_NO", packages);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable getCogfigration(string config)
       {
           DataTable data = new DataTable();
           sql = string.Format("select * from configraton where name='{0}'", config);
           data = ExecuteDataTable(sql);
           return data;
       }

       public DataTable ExecuteDataTable(string strSQL)
       {
           System.Diagnostics.Debug.WriteLine(strSQL);
           DataTable dt = new DataTable();
           OleDbConnection conn = new OleDbConnection(connStr);
           try
           {
               if (conn.State != ConnectionState.Open)
                   conn.Open();
               OleDbCommand cmd = new OleDbCommand();
               cmd.Connection = conn;
               cmd.CommandText = strSQL;
               OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
               int count = Da.Fill(dt);
               System.Diagnostics.Debug.WriteLine(dt.Rows.Count);
                System.Diagnostics.Debug.WriteLine(count);
               conn.Close();
           }
           catch (System.Exception ex)
           {
              // MessageBox.Show(ex.Message + ":" + strSQL);
               Logger.ErrorFormat("Excute < ExecuteNonQuery> {0} error: {1}", strSQL, ex.Message);
           }
           finally
           {
               conn.Close();
           }
           return dt;
       }

        public long ExecuteNonQueryReturnID(string strSQL)
        {
            long id = 0;
            System.Diagnostics.Debug.WriteLine(strSQL);
            DataTable dt = new DataTable();
            OleDbConnection conn = new OleDbConnection(connStr);
            try
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = conn;
                cmd.CommandText = strSQL;
                id = Int64.Parse(cmd.ExecuteScalar().ToString());                
                conn.Close();
            }
            catch (System.Exception ex)
            {
                // MessageBox.Show(ex.Message + ":" + strSQL);
                Logger.ErrorFormat("Excute < ExecuteNonQuery> {0} error: {1}", strSQL, ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return id;
        }

        public int ExecuteNonQuery(string strSQL)
        {
            System.Diagnostics.Debug.WriteLine(strSQL);
            int val = 1;
           using (OleDbConnection conn = new OleDbConnection(connStr))
               try
               {
                    OleDbCommand cmd = new OleDbCommand();
                   if (conn.State != ConnectionState.Open)
                       conn.Open();
                   cmd.Connection = conn;
                   cmd.CommandText = strSQL;
                   val = cmd.ExecuteNonQuery();
                   cmd.Parameters.Clear();
                   conn.Close();
               }
               catch (System.Exception ex)
               {
                  // MessageBox.Show(ex.Message);
                   conn.Close();
                   Logger.ErrorFormat("Excute < ExecuteNonQuery> {0} error: {1}", strSQL, ex.Message);
                   val = 0;
               }
           return val;
       }

       public int PackageToMES(string packageno,List<string> sheetnos)
       {
           int val = 0;
           using (OleDbConnection conn = new OleDbConnection(connStr))
           {              
               try
               {
                   if (conn.State != ConnectionState.Open)  conn.Open();
                    OleDbCommand cmd = conn.CreateCommand();
                  string sendtime = DateTime.Now.ToString("yyyyMMddHHmmss");
                  for (int i = 0; i < sheetnos.Count; i++)
                  {
                      sql = string.Format("insert into PACKAGE_TO_MES (PACKAGE_NO,SHEET_NO,SEND_TIME) values ('{0}','{1}','{2}')", packageno, sheetnos[i], sendtime);
                      cmd.CommandText = sql;
                      cmd.ExecuteNonQuery();
                      cmd.Parameters.Clear();
                  }
                  val = 1;
               }
               catch (Exception ex)
               {
               //  throw new Exception(sql, ex);
                   Logger.ErrorFormat("Excute < PackageToMES> {0} error: {1}", sql, ex.Message);
               }
               finally
               {
                   conn.Close();
               }
           }
           return val;
       }

       public int PackageToMES_NEW(string packageno, List<string> sheetnos)
       {
           int val = 0;
           using (OleDbConnection conn = new OleDbConnection(connStr))
           {
               if (conn.State != ConnectionState.Open)
                   conn.Open();
                OleDbCommand cmd = conn.CreateCommand();
                OleDbTransaction trans;
               trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);
               cmd.Transaction = trans;
               string sendtime = DateTime.Now.ToString("yyyyMMddHHmmss");
               try
               {
                   for (int i = 0; i < sheetnos.Count; i++)
                   {
                       sql = string.Format("insert into PACKAGE_TO_MES (PACKAGE_NO,SHEET_NO,SEND_TIME) values ('{0}','{1}','{2}')", packageno, sheetnos[i], sendtime);
                       cmd.CommandText = sql;
                       cmd.ExecuteNonQuery();
                       cmd.Parameters.Clear();
                   }
                   trans.Commit();
                   val = 1;
               }
               catch (Exception ex)
               {
                   trans.Rollback();
                   val = 0;
                  // throw new Exception(sql, ex);
                   Logger.ErrorFormat("Excute <PackageToMES_NEW> {0} error: {1}", sql, ex.Message);
               }
               finally
               {
                   conn.Close();
               }
           }
           return val;
       }

       public int UpdateplateData(List<string> sheetnos, string printpackageno)
       {
           int val = 0;
           using (OleDbConnection conn = new OleDbConnection(connStr))
           {
               try
               {
                   if (conn.State != ConnectionState.Open) conn.Open();
                    OleDbCommand cmd = conn.CreateCommand();
                   for (int i = 0; i < sheetnos.Count; i++)
                   {
                       sql = string.Format("update HTF_PLATE_DATA set PRINT_PACKAGE_NO='{0}' , PACKAGE_FLAG='1' where SHEET_NO='{1}' ", printpackageno,sheetnos[i]);
                       cmd.CommandText = sql;
                       cmd.ExecuteNonQuery();
                       cmd.Parameters.Clear();
                   }
                   val = 1;
               }
               catch (Exception ex)
               {
                   //throw new Exception(sql, ex);
                   Logger.ErrorFormat("Excute <UpdateplateData> {0} error: {1}", sql, ex.Message);
               }
               finally
               {
                   conn.Close();
               }
           }
           return val;
       }

       public int UpdatePlanData(List<string> sheetnos)
       {
           int val = 0;
           using (OleDbConnection conn = new OleDbConnection(connStr))
           {
               try
               {
                   if (conn.State != ConnectionState.Open) conn.Open();
                    OleDbCommand cmd = conn.CreateCommand();
                   for (int i = 0; i < sheetnos.Count; i++)
                   {
                       sql = string.Format("update HTF_PLAN_PRODUCE set UPPER_FLAG='1' where SHEET_NO='{0}' ", sheetnos[i]);
                       cmd.CommandText = sql;
                       cmd.ExecuteNonQuery();
                       cmd.Parameters.Clear();
                   }
                   val = 1;
               }
               catch (Exception ex)
               {
                  // throw new Exception(sql, ex);
                   Logger.ErrorFormat("Excute <UpdatePlanData> {0} error: {1}", sql, ex.Message);
               }
               finally
               {
                   conn.Close();
               }
           }
           return val;
       }




       public int ModifyPlateData(List<ModifyPlateData> modifyPlateData)
       {
           int val = 0;
           OleDbConnection conn = new OleDbConnection(connStr);
           try
               {                  
                   if (conn.State != ConnectionState.Open) conn.Open();
                OleDbCommand cmd = conn.CreateCommand();
                   for (int i = 0; i < modifyPlateData.Count; i++)
                   {
                       sql = string.Format("update HTF_PLATE_DATA set {0},MODIFY_FLAG='1'  where SHEET_NO='{1}' ", modifyPlateData[i].Values, modifyPlateData[i].sheetno);
                       cmd.CommandText = sql;
                       cmd.ExecuteNonQuery();
                       cmd.Parameters.Clear();
                       val = 1;
                   }
               }
               catch (Exception ex)
               {
                  // throw new Exception(sql, ex);
                   Logger.ErrorFormat("Excute <ModifyPlateData> {0} error: {1}", sql, ex.Message);
               }
               finally
               {
                   conn.Close();
               }
           return val;
       }

       public int InsertNewPlateData(List<ModifyPlateData> modifyPlateData)
       {
           int val = 0;
           using (OleDbConnection conn = new OleDbConnection(connStr))
           {
               try
               {
                   if (conn.State != ConnectionState.Open) conn.Open();
                    OleDbCommand cmd = conn.CreateCommand();
                   string sendtime = DateTime.Now.ToString("yyyyMMddHHmmss");
                   for (int i = 0; i < modifyPlateData.Count; i++)
                   {
                       sql = string.Format("insert into PLATE_DATA_MODIFY (SHEET_NO,SPLATE_LENGTH_ORIGINAL,SPLATE_LENGTH,SPLATE_WIDTH_ORIGINAL,SPLATE_WIDTH,SPLATE_THK_ORIGINAL,"
                                       + "SPLATE_THK,MOD_TIME) values ('{0}',{1},'{2}') ", modifyPlateData[i].sheetno, modifyPlateData[i].Values, sendtime);
                       cmd.CommandText = sql;
                       cmd.ExecuteNonQuery();
                       cmd.Parameters.Clear();
                       val = 1;
                   }
               }
               catch (Exception ex)
               {
                  // throw new Exception(sql, ex);
                   Logger.ErrorFormat("Excute <InsertNewPlateData> {0} error: {1}", sql,ex.Message);
                  
               }
               finally
               {
                   conn.Close();
               }
           }
           return val;
       }

       public int InsertSchedule(DataTable data)
       {
           int val = 0;
           using (OleDbConnection conn = new OleDbConnection(connStr))
           {
               try
               {
                   sql = "";
                   if (conn.State != ConnectionState.Open) conn.Open();
                   OleDbCommand cmd = conn.CreateCommand();
                   for (int i = 0; i < data.Rows.Count; i++)
                   {
                       string packageno = data.Rows[i]["PACKAGE_NO"].ToString();
                       string idex = data.Rows[i]["IDEX"].ToString();
                       string flag = data.Rows[i]["FLAG"].ToString();
                       string flag_prod = data.Rows[i]["FLAG_PROD"].ToString();
                       string planno = data.Rows[i]["PLAN_NO"].ToString();
                       string sampleno = data.Rows[i]["SAMPLE_NO"].ToString();
                       string steelgrade = data.Rows[i]["STEEL_GRADE"].ToString();
                       string stno = data.Rows[i]["ST_NO"].ToString();
                       string sendtime = data.Rows[i]["SENDTIME"].ToString();
                       string inpacknum = data.Rows[i]["IN_PACK_NUM"].ToString();
                       string inmatwt = data.Rows[i]["IN_MAT_WT"].ToString();

                       sql = string.Format("insert into HTF_PRODUCTION_SCHEDULE(PACKAGE_NO,IN_PACK_NUM,IN_MAT_WT,IDEX,SAMPLE_NO,PLAN_NO,STEEL_GRADE,ST_NO,FLAG,FLAG_PROD,SENDTIME ) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',"
                                      + " '{8}','{9}',to_date('{10}','yyyy/mm/dd hh24:mi:ss'))", packageno, inpacknum, inmatwt, idex, sampleno, planno, steelgrade, stno, flag, flag_prod, sendtime);
                       cmd.CommandText = sql;
                       cmd.ExecuteNonQuery();
                       cmd.Parameters.Clear();
                       val = 1;
                   }
               }
               catch (Exception ex)
               {
                  // throw new Exception(sql, ex);
                   Logger.ErrorFormat("Excute <InsertSchedule> {0} error: {1}", sql ,ex.Message);
               }
               finally
               {
                   conn.Close();
               }
           }
           return val;
       }
      

       public void SaveDatabase(DataTable data, string table)
       {
           OleDbConnection connection = new OleDbConnection(connStr);
           string sql = "SELECT * FROM  " + table + "  WHERE 1 = 0 ";

           try
           {
               connection.Open();
               OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);
               //OracleCommandBuilder builder = new OracleCommandBuilder(adapter);
               adapter.AcceptChangesDuringFill = false; // Important
               adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
               adapter.Update(data);
               adapter.Dispose();
           }
           catch (Exception ex)
           {
             //  throw new Exception(sql, ex);
               Logger.ErrorFormat("Excute <SaveDatabase> {0} error: {1}", table, ex.Message);
           }
           finally
           {
               connection.Close();
           }
       }


       public void UpdateShiftData(DataTable dt)
       {

       }

       public void GetCurrentShiftResult()
       { 

       }

       public static double SafeConvertDouble(object value)
       {
           return value is DBNull ? 0 : Convert.ToDouble(value);
       }
       public static Int32 SafeConvertInt32(object value)
       {
           return value is DBNull ? 0 : Convert.ToInt32(value);
       }
       public static string SafeConvertString(object value)
       {
           return value is DBNull ? "" : Convert.ToString(value);
       }
       public static DateTime SafeConvertDateTime(object value)
       {
           return value is DBNull ? DateTime.Now : Convert.ToDateTime(value);
       }
     
    }


     

   public class QueryArgs
   {
       public bool checkTime;
       public DateTime StartTime;
       public DateTime StopTime;

       public bool checkPackageNo;
       public string PackageNo;

       public bool checkSheetNo;
       public string SheetNo;

       public bool checkGrade;
       public string Grade;
   }

   class GridSelectData
   {
       #region 字段与属性


       private int _rowIndex;
       /// <summary>
       /// 获取或设置行索引。
       /// </summary>
       public int RowIndex
       {
           get { return _rowIndex; }
           set { _rowIndex = value; }
       }


       private string _columnName;
       /// <summary>
       /// 获取或设置列名称。
       /// </summary>
       public string ColumnName
       {
           get { return _columnName; }
           set { _columnName = value; }
       }


       private string _cellValve;
       /// <summary>
       /// 获取或设置单元格数据。
       /// </summary>
       public string CellValue
       {
           get { return _cellValve; }
           set { _cellValve = value; }
       }

       #endregion


       public GridSelectData()
       {
       }


       /// <summary>
       /// 存放指定单元格数据。
       /// </summary>
       /// <param name="rowIndex">行索引。</param>
       /// <param name="columnName">列名称。</param>
       /// <param name="cellValue">单元格数据。</param>
       public GridSelectData(int rowIndex, string columnName, string cellValue)
       {
           _rowIndex = rowIndex;
           _columnName = columnName;
           _cellValve = cellValue;
       }
   }

   public class sheetData
   {
       public string sheetno;
       public string packageno;
       public string planno;
       public string steelgrade;
       public string stno;
       public string length;
       public double thickness;
       public double width;
       public double weight;
       public string process;
       public string cooltype;
       public string shotblast;
       public double cooltemp;
       public double chargetempAim;
       public double chargetempMin;
       public double chargetempMax;
       public double inchargetimeAim;
       public double inchargetimeMin;
       public double inchargetimeMax;
       public double keeptimeAim;
       public double keeptimeMin;
       public double keeptimeMax;
       public string sampleno;
   }   

   public class sheetElement
   {
       public double ELEMENT_AL_VALUE;
       public double ELEMENT_AS_VALUE;
       public double ELEMENT_B_VALUE;
       public double ELEMENT_BE_VALUE;
       public double ELEMENT_BI_VALUE;
       public double ELEMENT_C_VALUE;
       public double ELEMENT_CA_VALUE;
       public double ELEMENT_CD_VALUE;
       public double ELEMENT_CO_VALUE;
       public double ELEMENT_CU_VALUE;
       public double ELEMENT_FE_VALUE;
       public double ELEMENT_GA_VALUE;
       public double ELEMENT_GE_VALUE;
       public double ELEMENT_H_VALUE;
       public double ELEMENT_LI_VALUE;
       public double ELEMENT_MG_VALUE;
       public double ELEMENT_MN_VALUE;
       public double ELEMENT_MO_VALUE;
       public double ELEMENT_N_VALUE;
       public double ELEMENT_NA_VALUE;
       public double ELEMENT_NB_VALUE;
       public double ELEMENT_NI_VALUE;
       public double ELEMENT_O_VALUE;
       public double ELEMENT_P_VALUE;
       public double ELEMENT_PB_VALUE;
       public double ELEMENT_RE_VALUE;
       public double ELEMENT_S_VALUE;
       public double ELEMENT_SB_VALUE;
       public double ELEMENT_SE_VALUE;
       public double ELEMENT_SI_VALUE;
       public double ELEMENT_SN_VALUE;
       public double ELEMENT_TA_VALUE;
       public double ELEMENT_TE_VALUE;
       public double ELEMENT_TI_VALUE;
       public double ELEMENT_V_VALUE;
       public double ELEMENT_W_VALUE;
       public double ELEMENT_ZN_VALUE;
       public double ELEMENT_ZR_VALUE;
       public double ELEMENT_SOL_AL_VALUE;
       public double ELEMENT_SOL_B_VALUE;
   }

   public class result
   {
       public string name;
       public string decr;
       public string value;
   }

   public  class checkresult
   {
       public string sheetno;
       public string type;
       public List<result> Result;
   }

   public class Modifyflag
   {
       public string sheetno;
       public bool length_flag;
       public bool width_flag;
       public bool thk_flag;
   }

   public class Modifysheet
   {
       public string sheetno;
       public bool length_flag;
       public bool width_flag;
       public bool thk_flag;
       public double length;
       public double width;
       public double thk;
   }

   public class ModifyPlateData
   {
       public string sheetno;
       public string  Values;
   }

}
